<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>MeowCAD Picture</title>

    <link rel="shortcut icon" href="/simpleoutline.ico" />
    <link rel="icon" href="/simpleoutline.ico" />

    <script type='text/javascript' src='/socket.io/socket.io.js' ></script>
    <!-- <script type='text/javascript' src='/js/lib/jquery.js'></script> -->
    <!-- <script type='text/javascript' src='/js/lib/jquery.cookie.js'></script> -->
    <script type='text/javascript' src='/js/jquery.js'></script> 
    <script type='text/javascript' src='/js/jquery.cookie.js'></script>

    <script type='text/javascript' src='js/meowmeow.js' ></script>

    <link rel="stylesheet" type="text/css" href="/css/font-awesome.min.css" />
    <!-- <link href="/bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css" /> -->
    <link rel="stylesheet" type="text/css" href="/bootstrap/css/bootstrap.css" />
    <script type="text/javascript" src="bootstrap/js/bootstrap.min.js"></script>



    <!--
    <link href="css/buttons.css" rel="stylesheet" type="text/css" />
    <link href="css/forms.css" rel="stylesheet" type="text/css" />
    <link href="css/tables.css" rel="stylesheet" type="text/css" />
    <link href="css/cleanlooks.css" rel="stylesheet" type="text/css" />
-->


    <script src='js/meowconfig.js'></script>
    <script>

      var g_lockedImg;
      var g_heartImg;

      var g_socket ;

      var g_userId;
      var g_sessionId;
      var g_picId;

      var g_activeSession = false;

      var g_clientToken = null;

      var g_isOwnerFlag = false;

      function processHandoff() 
      {

        console.log("processHandoff");

        if (g_activeSession)
        {

          console.log(" emitting picready");
          g_socket.emit("picready", 
          { userId : g_userId, 
            sessionId : g_sessionId , 
            clientToken : g_clientToken });
        }
        else
        {
          console.log("picready request not allowed for non authenticated visitors (must log in)");
        }
      }

      function processPic() {

        console.log("processPic");

        if (g_activeSession)
        {

          console.log("  emitting authenticated picpermission");

          g_socket.emit("picpermission", 
          { userId : g_userId, 
            sessionId : g_sessionId , 
            picId : g_picId });
        }
        else
        {

          console.log("  emitting anonymous picpermission");

          g_socket.emit("picpermission", {  picId : g_picId });
        }

      }


      $(document).ready( function() {
        meowmeow();

        var g_lockedImg = new Image();
        var g_heartImg = new Image();

        g_lockedImg.src = "img/locked.png";
        g_heartImg.src = "img/heart.png";

        if ( $.cookie("userId") && $.cookie("sessionId") )
        {
          //if ($.cookie("userName") && ($.cookie("userName") != "anonymous") )
          //{
            g_userId = $.cookie("userId");
            g_sessionId = $.cookie("sessionId");
            g_activeSession = true;
          //}
        }

        //g_socket = io.connect("https://localhost");
        //g_socket = io.connect("https://www.meowcad.com");
        g_socket = io.connect( MEOWURL );
        g_socket.on("picpermission", handlePicPermissionResponse );
        g_socket.on("picaccess", handlePicAccessResponse );
        g_socket.on("picready", handlePicReadyResponse );


        console.log("...");
        console.log( location.search.replace("?", '') );
        var s = location.search.replace('?', '').split('&').map(function(val){
            return val.split('=');
          });
        console.log(s);

        if ((s[0][0] == "action") && (s[0][1] == "handoff"))
        {
          if (s[1][0] == "clientToken")
          {
            g_clientToken = s[1][1];

            processHandoff();
            return;
          }

        }
        else if (s[0][0] == "id") 
        {
          g_picId = s[0][1];

          processPic();
          return;
        }

        console.log("unhandled case");

        var imgEle  = document.getElementById("imgContainer");
        imgEle.innerHTML = "Error processing request";

        return;

      });

      function handlePicAccessResponse( data )
      {
        console.log("handlePicAccessRsponse:");
        console.log(data);
      }

      function handlePicReadyResponse( data ) 
      {
        console.log("hanldPicReadyResponse:");
        console.log(data);

        message = data.message;
        stat    = data.status;
        type    = data.type;

        if ( stat == "success" )
        {
          g_picId = data.picId;

          console.log("picId:");
          console.log(g_picId);

          window.history.replaceState("", "", "pic?id=" + g_picId);
          processPic();
        }
        else
        {
          setTimeout(  processHandoff, 1000 );
        }
      }

      function handlePicPermissionResponse( data )
      {
        console.log("handlePicPermission:");
        console.log(data);

        if ( (data.type == "response") && (data.status == "success"))
        {


          console.log("got picpermission response!  using picId: " + g_picId );

          if (g_activeSession)
          {
            fetchPrivatePic( g_picId, g_userId, g_sessionId );

            var permission = data.permission;
            console.log("permission: " + permission);

            var flag = true;
            if ( $.cookie("userName") && ($.cookie("userName") == "anonymous") )
            {
              flag = false;
            }


            if ( ( data.editPermission == "allowed" ) && flag )
            {
              var b = document.getElementById('lockButton');
              b.style.display = "";
              b = document.getElementById('unlockButton');
              b.style.display = "";

              if (permission == "world-read")
              {
                unlockButton();
              }
              else 
              {
                lockButton();
              }
            }

          }
          else
          {
            fetchPublicPic( g_picId )
          }

        }

        // keep trying if in case it's not available
        //
        else
        {
          setTimeout( function() {

            console.log("trying for pic again");

            g_socket.emit("picpermission", { userId : g_userId, sessionId : g_sessionId , picId : g_picId });
          }, 1000);
        }

      }


      function lockButton()
      {
        console.log("lock");

        //img = document.getElementById("lockImage");
        //img.src = "/img/locked.png";

        msg = document.getElementById('lockedMessage');
        msg.innerHTML = "Image is currently locked and only viewable by you";
        msg.style.display = "";

        button = document.getElementById("lockButton");
        //button.className = "pure-button pure-button-lock";
        button.className = "btn btn-danger";
        button.innerHTML = "<i class='fa fa-lock'></i> " + "Locked";

        button = document.getElementById("unlockButton");
        //button.className = "pure-button pure-button-lock-unselected";
        button.className = "btn btn-default";
        button.innerHTML = "<i class='fa fa-heart'></i> " + "Unlock";
      }

      function sendLockMessage()
      {
        g_socket.emit("picaccess", { userId : g_userId, sessionId : g_sessionId , picId : g_picId, permission: "user" });
        lockButton();
      }


      function unlockButton()
      {
        console.log("unlock");

        //img = document.getElementById("lockImage");
        //img.src = "/img/heart.png";

        msg = document.getElementById('lockedMessage');
        msg.innerHTML = "Image is unlocked and viewable by everyone";
        msg.style.display = "";

        button = document.getElementById("lockButton");
        //button.className = "pure-button pure-button-lock-unselected";
        button.className = "btn btn-default";
        button.innerHTML = "<i class='fa fa-lock'></i> " + "Lock";

        button = document.getElementById("unlockButton");
        //button.className = "pure-button pure-button-unlock";
        button.className = "btn btn-success";
        button.innerHTML = "<i class='fa fa-heart'></i> " + "Unlocked";

      }

      function sendUnlockMessage()
      {
        g_socket.emit("picaccess", { userId : g_userId, sessionId : g_sessionId , picId : g_picId, permission: "world-read" });
        unlockButton();
      }

      function fetchPublicPic( picId )
      {

        console.log("fetching public pic: " + picId );

        var img = document.createElement("img");
        img.src = "picSentry.py?id=" + picId + "&dummy=" + Math.floor((Math.random()*10000)+1);

        img.className = "img-responsive";
        img.style.opacity = "0.95";
        img.style.border = "1px solid black";

        var div = document.getElementById("imgContainer");
        div.innerHTML = "";
        $("#imgContainer").append( img );

        var dlButton = document.getElementById("downloadButton");
        dlButton.style.display = '';
      }

      function fetchPrivatePic( picId, userId, sessionId )
      {

        console.log("fetching private pic: " + picId );


        var img = document.createElement("img");
        img.src = "picSentry.py?id=" + picId + "&userId=" + userId + "&sessionId=" + sessionId;

        img.className = "img-responsive";
        img.style.opacity = "0.95";
        img.style.border = "1px solid black";

        var div = document.getElementById("imgContainer");
        div.innerHTML = "";
        $("#imgContainer").append( img );

        var dlButton = document.getElementById("downloadButton");
        dlButton.style.display = '';
      }

      function downloadPicture()
      {

        if (g_picId)
        {
          console.log("downloading!");
          var ifrm = document.getElementById("downloadFrame");
          ifrm.src = "bleepsixDownloadManager.py?id=" + g_picId + "&name=pic.png" ;
        }
        else
        {
          console.log("cannot download");
        }

      }

    </script>


  </head>


  <body>

    <!--NAVBAR-->

    <div class="container">


      <div class='container-fluid'>
        <div class='row'>
          <div class='col-sm-4'>
            <h3 style='text-align:center;'>
              <i class='fa fa-camera' style='opacity:0.5;' ></i>
            </h3>
          </div>
          <div class='col-sm-4'> <h3 style='text-align:center; margin-bottom:25px;'>Snapshot</h3> </div>
          <div class='col-sm-4'> </div>
        </div>
      </div>



      <!--BREADCRUMB-->

      <!--MESSAGE-->


        <div class='container-fluid' style='margin-top:5px; margin-bottom:15px;' >
          <div class='row'>

            <!--
            <div class='col-sm-2'>
              <img  
                id='lockImage' 
                src='img/background.png' 
                height='42px' 
                width='42px' 
                style='display:block; opacity:0.5; margin:auto;'>
              </img>
            </div>
-->


            <div class='col-sm-2' style='text-align:center;' >
              <button 
                id='lockButton' 
                name='on' 
                value='on' 
                style='display:none; margin-bottom:10px;' 
                class="btn btn-danger"
                onclick='sendLockMessage();' >
                <i class='fa fa-lock'></i>
                Lock
              </button>
            </div>



            <div class='col-sm-2' style='text-align:center;' >
              <button 
                id='unlockButton' 
                name='off' 
                value='off' 
                style='display:none; margin-bottom:10px;' 
                class='btn btn-default'
                onclick='sendUnlockMessage();' >
                <i class='fa fa-unlock-alt'></i>
                Unlock</button>
            </div>

            <div class='col-sm-6' style='text-align:center; margin-bottom:10px; ' >
              <div id='lockedMessage' style='display:none;' >fetching...</div>
            </div>

            <div class='col-sm-2' style='text-align:center;' >
              <div 
                class='generic_button' 
                id='downloadButtonContainer' 
                style=' margin:auto; width:32px; height:32px; ' >
                <input 
                  id='downloadButton'
                  class='generic_button' 
                  type='image' 
                  src='img/download.png' 
                  style=' height:32px; width:32px; display:none; opacity:0.5; margin:auto;'
                  value='download' 
                  onclick='downloadPicture();' 
                />
              </div>

            </div>  <!-- row -->
          </div>  <!-- contianer fluid -->

        </div>

        <iframe id='downloadFrame' style='display:none'>
        </iframe>

        <div class='container-fluid'>
          <div class='row'>

            <!-- <div class='col-sm-1'></div> -->
            <div id='imgContainer' class='col-sm-12' style='text-align:center;' >
              Please wait while we fetch your picture...
            </div>
            <!-- <div class='col-sm-1'></div> -->

          </div>
        </div>


      <!--FOOTER-->

    </div>


    <!--ANALYTICS-->

  </body>
</html>



